<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能点餐 - 智能营养管理系统</title>
    <style>
        /* 基本样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8f9fa;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 15px;
        }
        
        .navbar {
            background-color: #007bff;
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
        }
        
        .navbar-brand {
            font-size: 1.5rem;
            font-weight: bold;
            color: white;
            text-decoration: none;
        }
        
        .page-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 2rem 0;
            border-radius: 10px;
            margin-bottom: 2rem;
            text-align: center;
        }
        
        .row {
            display: flex;
            flex-wrap: wrap;
            margin: -15px;
        }
        
        .col-md-3 {
            flex: 0 0 25%;
            max-width: 25%;
            padding: 15px;
        }
        
        .col-md-9 {
            flex: 0 0 75%;
            max-width: 75%;
            padding: 15px;
        }
        
        .col-md-4 {
            flex: 0 0 33.333333%;
            max-width: 33.333333%;
            padding: 15px;
        }
        
        .col-12 {
            flex: 0 0 100%;
            max-width: 100%;
            padding: 15px;
        }
        
        .card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 1.5rem;
            margin-bottom: 1rem;
            height: 100%;
        }
        
        .card-header {
            border-bottom: 1px solid #dee2e6;
            padding-bottom: 1rem;
            margin-bottom: 1rem;
        }
        
        .card-title {
            font-size: 1.25rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .list-group {
            list-style: none;
            padding: 0;
        }
        
        .list-group-item {
            padding: 0.75rem 0;
            border-bottom: 1px solid #dee2e6;
        }
        
        .list-group-item:last-child {
            border-bottom: none;
        }
        
        .list-group-item a {
            color: #007bff;
            text-decoration: none;
        }
        
        .list-group-item a:hover {
            color: #0056b3;
        }
        
        .dish-card {
            border: 1px solid #dee2e6;
            border-radius: 10px;
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .dish-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }
        
        .dish-image {
            width: 100%;
            height: 200px;
            background: linear-gradient(45deg, #f8f9fa, #e9ecef);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 3rem;
            color: #6c757d;
        }
        
        .dish-info {
            padding: 1rem;
        }
        
        .dish-name {
            font-size: 1.1rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .dish-description {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }
        
        .dish-nutrition {
            display: flex;
            justify-content: space-between;
            font-size: 0.8rem;
            color: #6c757d;
            margin-bottom: 1rem;
        }
        
        .dish-price {
            font-size: 1.2rem;
            font-weight: bold;
            color: #28a745;
            margin-bottom: 1rem;
        }
        
        .btn {
            display: inline-block;
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 5px;
            text-decoration: none;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #0056b3;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background-color: #218838;
        }
        
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        .text-center {
            text-align: center;
        }
        
        .text-muted {
            color: #6c757d;
        }
        
        .mb-3 {
            margin-bottom: 1rem;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1rem;
        }
        
        .alert-info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }

        /* 购物车样式 */
        .cart-sidebar {
            position: fixed;
            top: 0;
            right: -400px;
            width: 400px;
            height: 100vh;
            background: white;
            box-shadow: -2px 0 10px rgba(0,0,0,0.1);
            transition: right 0.3s ease;
            z-index: 1000;
            overflow-y: auto;
        }

        .cart-sidebar.open {
            right: 0;
        }

        .cart-header {
            padding: 1rem;
            border-bottom: 1px solid #eee;
            background: #f8f9fa;
        }

        .cart-content {
            padding: 1rem;
        }

        .cart-item {
            border-bottom: 1px solid #eee;
            padding: 1rem 0;
        }

        .cart-item:last-child {
            border-bottom: none;
        }

        .cart-item-name {
            font-weight: bold;
            margin-bottom: 0.5rem;
        }

        .cart-item-controls {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-top: 0.5rem;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .quantity-btn {
            width: 30px;
            height: 30px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .quantity-input {
            width: 50px;
            text-align: center;
            border: 1px solid #ddd;
            padding: 0.25rem;
        }

        .cart-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 999;
            display: none;
        }

        .cart-overlay.show {
            display: block;
        }

        .cart-toggle {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 1rem;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1001;
        }

        .cart-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #dc3545;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 0.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .meal-type-selector {
            margin-bottom: 1rem;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 5px;
        }

        @media (max-width: 768px) {
            .col-md-3, .col-md-9, .col-md-4 {
                flex: 0 0 100%;
                max-width: 100%;
            }

            .cart-sidebar {
                width: 100%;
                right: -100%;
            }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="container">
            <a class="navbar-brand" href="/">🍃 智能营养管理系统</a>
        </div>
    </nav>
    
    <div class="container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1>🍽️ 智能点餐</h1>
            <p>为您推荐营养均衡的美味菜品</p>
        </div>
        
        <div class="row">
            <!-- 侧边栏 - 分类 -->
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">菜品分类</h5>
                    </div>
                    <ul class="list-group">
                        <li class="list-group-item">
                            <a href="/meals">全部菜品</a>
                        </li>
                        <li class="list-group-item" th:each="category : ${categories}">
                            <a th:href="@{/meals(categoryId=${category.id})}" 
                               th:text="${category.name}">分类名称</a>
                        </li>
                        <li class="list-group-item" th:if="${#lists.isEmpty(categories)}">
                            <span class="text-muted">暂无分类</span>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-9">
                <!-- 菜品列表 -->
                <div class="row">
                    <div class="col-12" th:if="${dishPage != null and dishPage.hasContent()}">
                        <div class="row">
                            <div class="col-md-4" th:each="dish : ${dishPage.content}">
                                <div class="card dish-card">
                                    <div class="dish-image">
                                        🍽️
                                    </div>
                                    <div class="dish-info">
                                        <div class="dish-name" th:text="${dish.name}">菜品名称</div>
                                        <div class="dish-description" th:text="${dish.description}">菜品描述</div>
                                        <div class="dish-nutrition">
                                            <span th:text="'热量: ' + ${dish.calories} + 'kcal'">热量</span>
                                            <span th:text="'蛋白质: ' + ${dish.protein} + 'g'">蛋白质</span>
                                        </div>
                                        <div class="dish-price" th:text="'¥' + ${dish.price}">价格</div>
                                        <button class="btn btn-success btn-sm add-to-cart-btn"
                                                th:data-dish-id="${dish.id}"
                                                th:data-dish-name="${dish.name}"
                                                th:data-dish-calories="${dish.calories}"
                                                th:data-dish-price="${dish.price}">
                                            加入购物车
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-12" th:if="${dishPage == null or !dishPage.hasContent()}">
                        <div class="alert alert-info text-center">
                            <h5>暂无菜品</h5>
                            <p>系统正在准备美味菜品，请稍后再来查看。</p>
                            <a href="/" class="btn btn-primary">返回首页</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 购物车按钮 -->
    <button class="cart-toggle" onclick="toggleCart()">
        🛒
        <span class="cart-badge" id="cartBadge" style="display: none;">0</span>
    </button>

    <!-- 购物车遮罩 -->
    <div class="cart-overlay" id="cartOverlay" onclick="closeCart()"></div>

    <!-- 购物车侧边栏 -->
    <div class="cart-sidebar" id="cartSidebar">
        <div class="cart-header">
            <h5>购物车</h5>
            <button class="btn btn-sm btn-outline-secondary" onclick="closeCart()">关闭</button>
        </div>

        <!-- 餐别选择 -->
        <div class="meal-type-selector">
            <label for="mealTypeSelect">选择餐别：</label>
            <select id="mealTypeSelect" class="form-control">
                <option value="BREAKFAST">早餐</option>
                <option value="LUNCH">午餐</option>
                <option value="DINNER">晚餐</option>
                <option value="SNACK">小食</option>
            </select>
        </div>

        <div class="cart-content">
            <div id="cartItems">
                <div class="text-center text-muted">
                    购物车是空的
                </div>
            </div>

            <div id="cartSummary" style="display: none;">
                <hr>
                <div class="d-flex justify-content-between">
                    <strong>总计：</strong>
                    <strong id="cartTotal">¥0.00</strong>
                </div>
                <div class="d-flex justify-content-between text-muted">
                    <span>总热量：</span>
                    <span id="cartCalories">0 kcal</span>
                </div>
                <button class="btn btn-primary btn-block mt-3" onclick="submitOrder()">
                    提交订单
                </button>
                <button class="btn btn-outline-danger btn-block mt-2" onclick="clearCart()">
                    清空购物车
                </button>
            </div>
        </div>
    </div>

    <script>
        // 购物车数据
        let cart = [];

        // 根据当前时间自动设置餐别
        function setDefaultMealType() {
            const now = new Date();
            const hour = now.getHours();
            const mealTypeSelect = document.getElementById('mealTypeSelect');

            if (hour >= 6 && hour < 10) {
                mealTypeSelect.value = 'BREAKFAST';
            } else if (hour >= 10 && hour < 14) {
                mealTypeSelect.value = 'LUNCH';
            } else if (hour >= 14 && hour < 20) {
                mealTypeSelect.value = 'DINNER';
            } else {
                mealTypeSelect.value = 'SNACK';
            }
        }

        // 页面加载时设置默认餐别
        document.addEventListener('DOMContentLoaded', function() {
            setDefaultMealType();

            // 添加购物车按钮事件监听器
            document.querySelectorAll('.add-to-cart-btn').forEach(button => {
                button.addEventListener('click', function() {
                    try {
                        console.log('按钮数据:', this.dataset); // 调试日志

                        const dishId = parseInt(this.dataset.dishId);
                        const dishName = this.dataset.dishName;
                        const calories = parseFloat(this.dataset.dishCalories);
                        const price = parseFloat(this.dataset.dishPrice);

                        console.log('解析后的数据:', {dishId, dishName, calories, price}); // 调试日志

                        addToCart(dishId, dishName, calories, price);
                    } catch (error) {
                        console.error('添加到购物车时出错:', error);
                        showMessage('error', '添加到购物车失败: ' + error.message);
                    }
                });
            });
        });

        // 添加到购物车
        function addToCart(dishId, dishName, calories, price) {
            // 验证输入参数
            if (!dishId || !dishName) {
                showMessage('error', '菜品信息不完整');
                return;
            }

            // 确保数据类型正确
            const parsedDishId = parseInt(dishId);
            const parsedCalories = parseFloat(calories) || 0;
            const parsedPrice = parseFloat(price) || 0;

            if (isNaN(parsedDishId)) {
                showMessage('error', '菜品ID无效');
                return;
            }

            const existingItem = cart.find(item => item.dishId === parsedDishId);

            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push({
                    dishId: parsedDishId,
                    dishName: String(dishName),
                    calories: parsedCalories,
                    price: parsedPrice,
                    quantity: 1
                });
            }

            updateCartDisplay();
            showMessage('success', dishName + ' 已添加到购物车');
        }

        // 更新购物车显示
        function updateCartDisplay() {
            const cartBadge = document.getElementById('cartBadge');
            const cartItems = document.getElementById('cartItems');
            const cartSummary = document.getElementById('cartSummary');
            const cartTotal = document.getElementById('cartTotal');
            const cartCalories = document.getElementById('cartCalories');

            // 更新徽章
            const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
            if (totalItems > 0) {
                cartBadge.textContent = totalItems;
                cartBadge.style.display = 'flex';
            } else {
                cartBadge.style.display = 'none';
            }

            // 更新购物车内容
            if (cart.length === 0) {
                cartItems.innerHTML = '<div class="text-center text-muted">购物车是空的</div>';
                cartSummary.style.display = 'none';
            } else {
                cartItems.innerHTML = cart.map(item => `
                    <div class="cart-item">
                        <div class="cart-item-name">${item.dishName}</div>
                        <div class="text-muted">¥${item.price} | ${item.calories} kcal</div>
                        <div class="cart-item-controls">
                            <div class="quantity-control">
                                <button class="quantity-btn" onclick="updateQuantity(${item.dishId}, -1)">-</button>
                                <input type="number" class="quantity-input" value="${item.quantity}"
                                       onchange="setQuantity(${item.dishId}, this.value)" min="1">
                                <button class="quantity-btn" onclick="updateQuantity(${item.dishId}, 1)">+</button>
                            </div>
                            <button class="btn btn-sm btn-outline-danger" onclick="removeFromCart(${item.dishId})">删除</button>
                        </div>
                    </div>
                `).join('');

                // 计算总计
                const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
                const totalCalories = cart.reduce((sum, item) => sum + (item.calories * item.quantity), 0);

                cartTotal.textContent = '¥' + total.toFixed(2);
                cartCalories.textContent = totalCalories.toFixed(0) + ' kcal';
                cartSummary.style.display = 'block';
            }
        }

        // 更新数量
        function updateQuantity(dishId, change) {
            const item = cart.find(item => item.dishId === dishId);
            if (item) {
                item.quantity += change;
                if (item.quantity <= 0) {
                    removeFromCart(dishId);
                } else {
                    updateCartDisplay();
                }
            }
        }

        // 设置数量
        function setQuantity(dishId, quantity) {
            const item = cart.find(item => item.dishId === dishId);
            if (item) {
                const newQuantity = parseInt(quantity);
                if (newQuantity > 0) {
                    item.quantity = newQuantity;
                    updateCartDisplay();
                } else {
                    removeFromCart(dishId);
                }
            }
        }

        // 从购物车移除
        function removeFromCart(dishId) {
            cart = cart.filter(item => item.dishId !== dishId);
            updateCartDisplay();
        }

        // 清空购物车
        function clearCart() {
            cart = [];
            updateCartDisplay();
            showMessage('info', '购物车已清空');
        }

        // 切换购物车显示
        function toggleCart() {
            const sidebar = document.getElementById('cartSidebar');
            const overlay = document.getElementById('cartOverlay');

            if (sidebar.classList.contains('open')) {
                closeCart();
            } else {
                sidebar.classList.add('open');
                overlay.classList.add('show');
            }
        }

        // 关闭购物车
        function closeCart() {
            const sidebar = document.getElementById('cartSidebar');
            const overlay = document.getElementById('cartOverlay');

            sidebar.classList.remove('open');
            overlay.classList.remove('show');
        }

        // 提交订单
        function submitOrder() {
            if (cart.length === 0) {
                showMessage('error', '购物车是空的');
                return;
            }

            const mealTypeSelect = document.getElementById('mealTypeSelect');
            if (!mealTypeSelect) {
                showMessage('error', '请选择餐别');
                return;
            }

            const mealType = mealTypeSelect.value;
            if (!mealType) {
                showMessage('error', '请选择餐别');
                return;
            }

            // 构建订单数据 - 确保数据格式正确
            const orderData = cart.map(item => {
                // 验证必要字段
                if (!item.dishId || !item.dishName || !item.quantity) {
                    throw new Error('购物车数据不完整');
                }

                return {
                    dishId: parseInt(item.dishId),
                    dishName: String(item.dishName),
                    mealType: String(mealType),
                    portionSize: parseFloat(item.quantity) || 1.0,
                    price: parseFloat(item.price) || 0.0
                };
            });

            console.log('提交订单数据:', orderData); // 调试日志

            // 提交订单到批量订单端点
            fetch('/meals/api/orders/batch', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(orderData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('订单响应:', data); // 调试日志
                if (data.success) {
                    showMessage('success', data.message);
                    clearCart();
                    closeCart();
                } else {
                    showMessage('error', data.message || '订单提交失败');
                }
            })
            .catch(error => {
                console.error('订单提交错误:', error);
                showMessage('error', '网络错误，请重试: ' + error.message);
            });
        }

        // 显示消息
        function showMessage(type, message) {
            // 创建消息元素
            const messageDiv = document.createElement('div');
            messageDiv.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} alert-dismissible`;
            messageDiv.style.position = 'fixed';
            messageDiv.style.top = '20px';
            messageDiv.style.left = '50%';
            messageDiv.style.transform = 'translateX(-50%)';
            messageDiv.style.zIndex = '9999';
            messageDiv.innerHTML = `
                ${message}
                <button type="button" class="close" onclick="this.parentElement.remove()">
                    <span>&times;</span>
                </button>
            `;

            document.body.appendChild(messageDiv);

            // 3秒后自动移除
            setTimeout(() => {
                if (messageDiv.parentElement) {
                    messageDiv.remove();
                }
            }, 3000);
        }
    </script>
</body>
</html>
